import axios from 'axios';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { AxiosRequestConfig, AxiosRequestHeaders } from 'axios';
import { message } from 'antd';
const instance = axios.create({
    baseURL: process.env.REACT_APP_URL,
});
instance.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        const token = sessionStorage.getItem('frieneed-admin-satoken');
        if (token) {
            (config.headers as AxiosRequestHeaders)['frieneed-admin-satoken'] = token;
        }
        (config.headers as AxiosRequestHeaders)['Accept-Language'] = 'en-US';
        return config;
    },
    error => {
        Promise.reject(error);
    }
);

const AxiosInterceptor = ({ children }: any) => {
    const navigate = useNavigate();
    const logIn = () => {
        sessionStorage.clear();
        localStorage.clear();
        navigate('/login');
    };
    const resInterceptor = (response: any) => {
        const code = response.data.code;
        switch (code) {
            case 90002:
                message.error('Token is null');
                logIn();
                break;
            case 90003:
                message.error('Invalid token');
                logIn();
                break;
            case 90004:
                message.error('Token has expired');
                logIn();
                break;
            case 90006:
                logIn();
                break;
            case 90008:
                message.error('Token has been topped offline');
                logIn();
                break;
            case 90009:
                message.error('Token has been kicked offline');
                logIn();
                break;
            default:
                if (response.headers[`frieneed-admin-satoken`])
                    sessionStorage.setItem(`frieneed-admin-satoken`, response.headers[`frieneed-admin-satoken`]);
                return response;
        }
    };

    const errInterceptor = (error: any) => {
        return Promise.reject(error);
    };

    const interceptor = instance.interceptors.response.use(resInterceptor, errInterceptor);
    useEffect(() => {
        return () => instance.interceptors.response.eject(interceptor);
    }, [navigate]);

    return children;
};

export default instance;
export { AxiosInterceptor };
